package org.ms.mconf.sdk.model;

import com.alibaba.fastjson.JSON;
import lombok.*;
import org.ms.mconf.sdk.Constants;

import java.io.Serializable;

/**
 * The Node Multi Config
 *
 * @author lry
 */
@Data
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class NodeMultiConfig implements Serializable {

    /**
     * The application node config
     */
    private NodeConfig application;

    /**
     * The config node config
     */
    private NodeConfig config;

    /**
     * The version node config
     */
    private NodeConfig version;

    public NodeMultiConfig(String application, String config, String version) {
        this.application = new NodeConfig(application);
        this.config = new NodeConfig(config);
        this.version = new NodeConfig(version);
    }

    public static String buildKey(String group) {
        return String.join(Constants.DELIMITER, group, Constants.ACV_KEY);
    }

    public static String buildMatchKey(String group, String node, String environment) {
        return String.join(Constants.DELIMITER, group, Constants.ACV_KEY,
                isBlank(node) ? Constants.MATCH_ALL : node,
                isBlank(environment) ? Constants.MATCH_ALL : environment);
    }

    public static String buildField(NodeMultiConfig m) {
        return String.join(Constants.DELIMITER, m.getApplication().getId(), m.getConfig().getId(), m.getVersion().getId());
    }

    public static String buildValue(NodeMultiConfig nodeMultiConfig) {
        return JSON.toJSONString(nodeMultiConfig);
    }

    public static NodeMultiConfig parseValue(String value) {
        return JSON.parseObject(value, NodeMultiConfig.class);
    }

    private static boolean isBlank(String str) {
        return str == null || str.length() == 0;
    }

}
